package com.bdmc.smokesensor.Utils.http;

import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.bdmc.smokesensor.Utils.CommonUtil;

import org.apache.http.Header;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class HttpAPIService {

    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;

    public static final Logger logger = LoggerFactory.getLogger((HttpAPIService.class));
    private static String ROOTURL = "http://api.3jyun.com";
    private static String DEVICEID = "18928055888_jmz0o1j2";
    private static String MONITORID = "169";
    private static String COMMANDPATH = "/third/nb/north/command";
    private static String DEVDETAIL = "/third/rms/aaa/devDetail";
    private static String DELETEDEVICE = "/third/rms/device/monitor";
    private static String DEVICESECRET = "88f430c0722c7405c6a68a569ab32f2e";

    /**
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url, Header[] headers) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeaders(headers);
        httpGet.setConfig(config);
        logger.debug("GET请求地址：" + url);
        CloseableHttpResponse response = this.httpClient.execute(httpGet);
        HttpResult result = new HttpResult(response.getStatusLine().getStatusCode(),
                EntityUtils.toString(response.getEntity()));
        logger.debug("GET响应状态码：" + result.getCode() + "。内容：" + result.getBody());
        return result;
    }

    /**
     * 
     * @param url     请求地址，包含参数，因为有些是浏览器地址后面直接加id，有些是?id=xxx
     * @param headers 请求头
     * @return
     * @throws Exception
     */
    public HttpResult doDelete(String url, Header[] headers) throws Exception {
        HttpDelete httpDelete = new HttpDelete(url);
        httpDelete.setHeaders(headers);
        httpDelete.setConfig(config);
        logger.debug("DELETE请求地址：" + url);
        CloseableHttpResponse response = this.httpClient.execute(httpDelete);
        HttpResult result = new HttpResult(response.getStatusLine().getStatusCode(),
                EntityUtils.toString(response.getEntity(), "UTF-8"));
        logger.debug("DELETE响应状态码：" + result.getCode() + "。内容：" + result.getBody());
        return result;
    }

    /**
     * 带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url, Map<String, Object> map, Header[] headers) throws Exception {
        String newurl = buildGetParams(url, map);
        // 调用不带参数的get请求
        return this.doGet(newurl, headers);
    }

    // 拼接get参数
    private String buildGetParams(String url, Map<String, Object> map) throws URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(url);

        if (map != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }
        return uriBuilder.build().toString();
    }

    /**
     * 带参数的post请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url, Map<String, Object> map, Header[] headers) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        httpPost.setHeaders(headers);
        logger.debug("POST请求地址" + url);
        // 判断map是否为空，不为空则进行遍历，封装from表单对象
        if (map != null) {
            // List<NameValuePair> list = new ArrayList<NameValuePair>();
            JSONObject jsonParam = new JSONObject();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // list.add(new BasicNameValuePair(entry.getKey(),
                // entry.getValue().toString()));
                jsonParam.put(entry.getKey(), entry.getValue().toString());
            }
            // 构造from表单对象
            // UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list,
            // "UTF-8");
            // 构造json表单对象
            StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");// 解决中文乱码问题
            // 把表单放到post里
            httpPost.setEntity(entity);
            logger.debug("POST请求参数：" + jsonParam.toString());
        }

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        HttpResult result = new HttpResult(response.getStatusLine().getStatusCode(),
                EntityUtils.toString(response.getEntity()));
        logger.debug("POST响应状态码：" + result.getCode() + "。内容：" + result.getBody());
        return result;
    }

    /**
     * 不带参数post请求
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url, Header[] headers) throws Exception {
        return this.doPost(url, null, headers);
    }

    /**
     * 控制设备指令，消音等
     * 
     * @param deviceId 设备id
     * @param command  命令 “5859”： 是类型为'CTNBSmokeSensor'的设备的远程消音指令
     * @return
     * @throws Exception
     */
    public HttpResult doGetCommand(String deviceId, String command) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("deviceId", deviceId);
        map.put("command", command);
        String path = buildGetParams(COMMANDPATH, map);
        String timestamp = getCurrentTimeStamp();
        String sign = getSignature(path, timestamp);
        return this.doGet(ROOTURL + path, assemblyHeader(sign, timestamp));
    }

    /**
     * 获取单个设备信息
     * 
     * @param deviceId 设备id
     * @return
     * @throws Exception
     */
    public HttpResult doGetDevDetail(String deviceId) throws Exception {
        String url = ROOTURL + DEVDETAIL + "/" + deviceId;
        String timestamp = getCurrentTimeStamp();
        String sign = getSignature(DEVDETAIL + "/" + deviceId, timestamp);
        return this.doGet(url, assemblyHeader(sign, timestamp));
    }

    /**
     * 删除单个设备
     * 
     * @param deviceId 设备id
     * @return
     * @throws Exception
     */
    public HttpResult doDeleteDev(String deviceId) throws Exception {
        String url = ROOTURL + DELETEDEVICE + "/" + deviceId;
        String timestamp = getCurrentTimeStamp();
        String sign = getSignature(DELETEDEVICE + "/" + deviceId, timestamp);
        return this.doGet(url, assemblyHeader(sign, timestamp));
    }

    private static String getCurrentTimeStamp() {
        return Calendar.getInstance().getTimeInMillis() + "";
    }

    /**
     * 组装头部信息
     * 
     * @param headers
     * @return
     */
    private static Header[] assemblyHeader(String sign, String timestamp) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("DeviceId", DEVICEID);
        headers.put("MonitorId", MONITORID);
        headers.put("Timestamp", timestamp);
        headers.put("Signature", sign);
        headers.put("Content-Type", "application/json;charset=UTF-8");
        Header[] allHeader = new BasicHeader[headers.size()];
        int i = 0;
        for (String str : headers.keySet()) {
            allHeader[i] = new BasicHeader(str, headers.get(str));
            i++;
        }
        return allHeader;
    }

    private String getSignature(String path, String timestamp) {
        return CommonUtil.MD5(path + timestamp + DEVICESECRET).toLowerCase();
    }
}
